#include "TB_searchTitleGoodrate.h"

#include "MW_WebEngineView.h"

// 网址中参数："isb=0":是指淘宝店？"isb=1":是指天猫店？貌似是的，数量上对的上。
// 网页上选择好评率"100%"生成的链接：https://shopsearch.taobao.com/search?q=龟&rele_field=title&goodrate=10000%2C10080
// 网页上选择好评率"99%以上"生成的链接：https://shopsearch.taobao.com/search?q=龟&rele_field=title&isb=0&goodrate=9900%2C
// ZC: 好评率100%的店铺数量 也太多:超过2000了...
int g_iiPercentPoint[] = {0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 7500, 8000, 8500,
	9000, 9100, 9200, 9300, 9400, 9500, 9600, 9700, 9800, 9900};


TB_searchTitleGoodrate::TB_searchTitleGoodrate(void *_pmvWebEngineView, QWebEngineView* _pweView, QString _strKeyword):
    WebRequestBase(_pmvWebEngineView, _pweView, _strKeyword)
{
    FdtInterval = QDateTime::currentDateTime();
}

void TB_searchTitleGoodrate::SetExtendInfo(QString _strIniFile)
{
    FstrIniFile = _strIniFile;
}

void TB_searchTitleGoodrate::Request(int iType)
{
    if (iType == (int)tbrtLogin)
        FpweView->setUrl(QUrl("https://login.taobao.com/member/login.jhtml"));
    else
    {
        if (FiSearchIdx == 0)
            FpweView->setUrl("https://shopsearch.taobao.com/search?q="+FstrKeyword+"&ie=utf8&rele_field=title&goodrate=0000%2C1000");
    }
    Fwrt = wrtProcessPercent100;
}

int TB_searchTitleGoodrate::IfResponse_byType(EWebResponseType _type)
{
    qDebug() << "IfResponse_byType(...) : "<<_type << Fwrt;
    if (_type == Fwrt)
    {
        QDateTime dt = QDateTime::currentDateTime();
        qint64 i64Pass = FdtInterval.msecsTo(dt);
        FdtInterval = dt;
        qDebug() << "i64Pass:" << i64Pass;
        if (i64Pass < 1000)
            return -1;// 1秒以内不重复触发相同事件

        return 1000;
    }
    return -1;
}

bool TB_searchTitleGoodrate::Response()
{
    qDebug() << "TB_searchTitleGoodrate::LoadFinished(...) - " << FpweView->url().url();
//    bool bStartsWith = FpweView->url().url().startsWith("https://shopsearch.taobao.com/search?q="+FstrKeyword);
//    qDebug() << "bStartsWith:"<<bStartsWith;
//    if (!bStartsWith)
//        return false;

    QWebEnginePage *pPage = FpweView->page();

    // ZC: 登陆
    if (FpweView->url().url().startsWith("https://login.taobao.com/member/login"))// https://login.taobao.com/member/login.jhtml
    {
        QString userName, pw;
        MW_WebEngineView::Ini_JieMi(FstrIniFile, "taobao_login", "username", &userName);
        MW_WebEngineView::Ini_JieMi(FstrIniFile, "taobao_login", "pw", &pw);
        //qDebug() << "FstrIniFile:" << FstrIniFile;
        //qDebug() << "userName:" << userName;

        pPage->runJavaScript("document.body.scrollLeft=500;");
        //var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;

        QString strJsBlock;
        FjsOper.JsBlockGetByFnName("E:\\Gitee\\Qt_Test\\JavaScript\\zz01.js", "TB_DeleteFirstElementByClassName", strJsBlock);
        strJsBlock += "TB_DeleteFirstElementByClassName('div', 'login-newbg');";
        pPage->runJavaScript(strJsBlock);

        strJsBlock.clear();
        FjsOper.JsBlockGetByFnName("E:\\Gitee\\Qt_Test\\JavaScript\\zz01.js", "TB_SetLoginUsername", strJsBlock);
        strJsBlock += "TB_SetLoginUsername('fm-login-id', '"+userName+"');";
        pPage->runJavaScript(strJsBlock);

        strJsBlock.clear();
        FjsOper.JsBlockGetByFnName("E:\\Gitee\\Qt_Test\\JavaScript\\zz01.js", "TB_input_setValueById", strJsBlock);
        strJsBlock += "TB_input_setValueById('fm-login-password', '"+pw+"');";
        pPage->runJavaScript(strJsBlock);

        strJsBlock.clear();
        FjsOper.JsBlockGetByFnName("E:\\Gitee\\Qt_Test\\JavaScript\\zz01.js", "TB_ButtonClick_byClassName", strJsBlock);
        strJsBlock += "TB_ButtonClick_byClassName('fm-button fm-submit password-login');";
        pPage->runJavaScript(strJsBlock);

        pPage->runJavaScript("console.log('zzzzz')");// ZC: 这个 打印不出来？
    }
    // ZC: 登陆成功，跳转到这个页面
    else if (FpweView->url().url().startsWith("https://i.taobao.com/my_taobao.htm"))// https://i.taobao.com/my_taobao.htm?nekot=b2ttbmppNzk1MTM=1590976483688
    {
        //FweView.setUrl(QUrl("https://s.taobao.com/"));
        //FweView.setUrl(QUrl("https://shopsearch.taobao.com/search?q=龟&ie=utf8&rele_field=title&goodrate=9300%2C9500"));

        FiSearchIdx = 0;
        Request((int)tbrtSearch_DianPuMingCheng_HaiPingLv);
    }

    else if (FpweView->url().url().startsWith("https://shopsearch.taobao.com/search?"))
    {
        if (FiSearchIdx == 0)
        {
            QString strJsBlock;
            FjsOper.JsBlockGetByFnName("E:\\Gitee\\Qt_Test\\JavaScript\\zz01.js", "Element_by_tagName_className", strJsBlock);
            strJsBlock += "var ele = Element_by_tagName_className('span', 'shop-count');\r\n";
            QString strJsBlock1;
            FjsOper.JsBlockGetByFnName("E:\\Gitee\\Qt_Test\\JavaScript\\zz01.js", "InnerText_by_parent_tagName", strJsBlock1);
            strJsBlock += strJsBlock1+"\r\n InnerText_by_parent_tagName(ele, 'b');";
			ScriptCallback1 *pscb = new ScriptCallback1(this, jtShopCount);
            qDebug() << "pscb:" << pscb;
            pPage->runJavaScript(strJsBlock, *pscb);
            qDebug() << "After runJavaScript(...)";
            delete pscb;
        }


//        QString strJsBlock;
//        FjsOper.JsBlockGetByFnName("E:\\Gitee\\Qt_Test\\JavaScript\\zz01.js", "ScrollWindow", strJsBlock);
//        strJsBlock += "ScrollWindow(1, 13000);";
//        pPage->runJavaScript(strJsBlock);

//        strJsBlock.clear();
//        FjsOper.JsBlockGetByFnName("E:\\Gitee\\Qt_Test\\JavaScript\\zz01.js", "ShopInfoList", strJsBlock);
//        strJsBlock += "ShopInfoList();";

//        ScriptCallback1 *pscb = new ScriptCallback1(this, jtShopInfoList);
//        pPage->runJavaScript(strJsBlock, *pscb);
////        pPage->runJavaScript(strJsBlock,
////                             [] (const QVariant &result) {
////            qDebug()<<result.toString();
////        });

    }


    else if (FpweView->url().url().startsWith("https://s.taobao.com/"))
    {
        QString strJsBlock;
        FjsOper.JsBlockGetByFnName("E:\\Gitee\\Qt_Test\\JavaScript\\zz01.js", "TB_DeleteElementById", strJsBlock);
        strJsBlock += "TB_DeleteElementById('stblogo');";
        pPage->runJavaScript(strJsBlock);
//        AddMsg("");
//        AddMsg("strJsBlock: ");
//        AddMsg(strJsBlock);

        strJsBlock.clear();
        FjsOper.JsBlockGetByFnName("E:\\Gitee\\Qt_Test\\JavaScript\\zz01.js", "Click_by_TagName_innerText", strJsBlock);
        strJsBlock += "Click_by_TagName_innerText('a', '店铺');";
        pPage->runJavaScript(strJsBlock);

        strJsBlock.clear();
        FjsOper.JsBlockGetByFnName("E:\\Gitee\\Qt_Test\\JavaScript\\zz01.js", "TB_input_setValueById", strJsBlock);
        strJsBlock += "TB_input_setValueById('q', '龟');";
        pPage->runJavaScript(strJsBlock);
//        AddMsg("");
//        AddMsg("strJsBlock: ");
//        AddMsg(strJsBlock);

        strJsBlock.clear();
        FjsOper.JsBlockGetByFnName("E:\\Gitee\\Qt_Test\\JavaScript\\zz01.js", "TB_ButtonClick_byClassName", strJsBlock);
        strJsBlock += "TB_ButtonClick_byClassName('btn-search');";
        pPage->runJavaScript(strJsBlock);


    }
//    else
//    {}
    return true;
}

void TB_searchTitleGoodrate::JsReturn(int _iJsType, const QVariant &result, ScriptCallback1 *_pScriptCallback)
{
    qDebug() << "JsReturn(...) -- result.type():"<<result.type() << ", _iJsType:" << (EJsType)_iJsType << ", _pScriptCallback:" << _pScriptCallback;
    //delete _pScriptCallback;

	const int SHOP_COUNT_PER_PAGE = 20;

	if (_iJsType == (int)jtShopCount)
	{
		QString strShopCount = result.toString();
        if (strShopCount.isEmpty())
			return;

		int iShopCount = strShopCount.toInt();
		if (iShopCount % SHOP_COUNT_PER_PAGE == 0)
			FiPageCount = iShopCount / SHOP_COUNT_PER_PAGE;
		else
			FiPageCount = iShopCount / SHOP_COUNT_PER_PAGE + 1;

	    FiPageIndex = 0;
        qDebug() << "FiPageIndex:"<<FiPageIndex<<", FiPageCount:"<<FiPageCount << ", strShopCount:" << strShopCount;
	}
	else if (_iJsType == (int)jtShopInfoList)
	{
        AddMsg("result.type():"+QString::number((int)result.type()));

		if (result.type() == QVariant::Type::List)
		{
			QVariantList* pVarList = (QVariantList*)&result;
			if (pVarList->count()>0)
			{
				qDebug() <<"pVarList->count():"<<pVarList->count();
				for (int i=0; i<pVarList->count(); i++)
				{
					QVariant vv = pVarList->at(i);
					//qDebug() <<"vv.type():"<<vv.type();
					if (vv.type() == QVariant::Type::String)
					{
						qDebug() << i << ":" <<vv.toString();
					}
				}
			}
		}
		else if (result.type() == QVariant::Type::String)
			qDebug() <<result.toString();
	}
}

void TB_searchTitleGoodrate::AddMsg(QString _str)
{
    ((MW_WebEngineView*)FpmvWebEngineView)->AddMsg(_str);
}
